package cn.zzq.shop.goods.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.zzq.shop.common.util.ConstatFinalUtil;
import cn.zzq.shop.common.util.PageInfoUtil;
import cn.zzq.shop.common.util.RedisUtil;
import cn.zzq.shop.goods.dao.IAGoodsBrandDao;
import cn.zzq.shop.goods.dao.IAGoodsCateDao;
import cn.zzq.shop.goods.dao.IAGoodsDao;
import cn.zzq.shop.goods.pojo.AGoods;
import cn.zzq.shop.goods.pojo.AGoodsBrand;
import cn.zzq.shop.goods.pojo.AGoodsCate;
import cn.zzq.shop.goods.service.IGoodsService;

@Service("goodsService")
public class GoodsServiceImpl implements IGoodsService
{
	@Resource
	private IAGoodsBrandDao goodsBrandDao;
	@Resource
	private IAGoodsCateDao goodsCateDao;
	@Resource
	private IAGoodsDao goodsDao;
	@Resource
	private RedisUtil redisUtil;
	@Override
	public AGoodsBrand findOneGoodsBrandService(Map<String, Object> condMap)
	{
		return this.goodsBrandDao.findOne(condMap);
	}
	
	@Override
	public JSONObject saveOneGoodsBrandService(AGoodsBrand goodsBrand)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsBrandDao.save(goodsBrand);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsBrand.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject saveOneGoodsBrandService(AGoodsBrand goodsBrand,Map<String, Object> paramsMap)
	{
		/* 保存品牌 */
		JSONObject resultJSON = this.saveOneGoodsBrandService(goodsBrand);
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneGoodsBrandService(AGoodsBrand goodsBrand)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsBrandDao.update(goodsBrand);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsBrand.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneGoodsBrandService(AGoodsBrand goodsBrand,Map<String, Object> paramsMap)
	{
		JSONObject resultJSON = this.updateOneGoodsBrandService(goodsBrand);
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneGoodsBrandService(AGoodsBrand goodsBrand)
	{
		JSONObject resultJSON = new JSONObject();
		return resultJSON;
	}
	
	@Override
	public Map<String,Object> findCondListGoodsBrandService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/* 为关键字加上%,实现模糊匹配 
		 * */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		if(pageInfoUtil != null)
		{
			/* 分页 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			/* 查询总记录数 */
			List<AGoodsBrand> goodsList = this.goodsBrandDao.findList(condMap);
			/* 使用Dubbo的时候,不能为参数新增加赋值 */
			pageInfoUtil.setTotalRecord(Long.valueOf(page.getTotal()).intValue());
			
			resultMap.put("list", goodsList);
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			return resultMap;
		}
		/* 不分页查询数据 */
		List<AGoodsBrand> goodsList= this.goodsBrandDao.findList(condMap);
		resultMap.put("list", goodsList);
		return resultMap ; 
	}
	
	@Override
	public AGoodsCate findOneGoodsCateService(Map<String, Object> condMap)
	{
		return this.goodsCateDao.findOne(condMap);
	}
	
	@Override
	public JSONObject saveOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsCateDao.save(goodsCate);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsCate.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsCateDao.update(goodsCate);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsCate.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		return resultJSON;
	}
	
	@Override
	public Map<String, Object> findCondListGoodsCateService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<>();
		/* 为关键字加上%,实现模糊匹配 
		 * */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		if(pageInfoUtil != null)
		{
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			List<AGoodsCate> roleList = this.goodsCateDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			resultMap.put("total", pageInfoUtil.getTotalRecord());
			resultMap.put("list", roleList);
			return resultMap;
		}
		/* 不分页查询数据 */
		List<AGoodsCate> roleList = this.goodsCateDao.findList(condMap);
		resultMap.put("list", roleList);
		return resultMap;
	}
	
	/*查询树形结构分类*/
	public List<AGoodsCate> findTreeListCateService(){
		
		/* 存储结果 */
		List<AGoodsCate> resultList = new ArrayList<AGoodsCate>();
		Map<String, Object> condMap = new HashMap<>();
		condMap.put("parentId", "0");
		Map<String, Object> resultMap = this.findCondListGoodsCateService(null, condMap);
		List<AGoodsCate> cateList = (List<AGoodsCate>) resultMap.get("list");
		
		for (Iterator iterator = cateList.iterator(); iterator.hasNext();)
		{
			AGoodsCate goodsCate = (AGoodsCate) iterator.next();
			this.findTreeListCateServiceUtil(goodsCate,0,resultList);
		}
		return resultList;
	}
	
	/*递归查询分类信息*/
	private void findTreeListCateServiceUtil(AGoodsCate goodsCate, int level, List<AGoodsCate> goodsCateList)
	{
		/*增加前置字符串*/
		StringBuffer preStrSb = new StringBuffer();
		for (int i = 0; i < level; i++)
		{
			preStrSb.append("|-->");
		}
		/*列出树形结构*/
		goodsCate.setTreeName(preStrSb.toString()+goodsCate.getName());
		/*增加到容器中*/
		goodsCateList.add(goodsCate);
		
		/*查询子节点*/
		Map<String, Object> condMap = new HashMap<>();
		condMap.put("parentId", goodsCate.getId());
		Map<String, Object> resultMap = this.findCondListGoodsCateService(null, condMap);
		List<AGoodsCate> childList = (List<AGoodsCate>) resultMap.get("list");
		if(childList.size() > 0){
			/*非叶子结点*/
			goodsCate.setLeafStatus("0");
			for (Iterator iterator = childList.iterator(); iterator.hasNext();)
			{
				AGoodsCate cateTemp = (AGoodsCate) iterator.next();
				/*自己调用自己*/
				this.findTreeListCateServiceUtil(cateTemp, level+1, goodsCateList);
			}
		}else {
			/*叶子节点*/
			goodsCate.setLeafStatus("1");
		}
	}

	/**
	 * 商品模块开始
	 */
	@Override
	public AGoods findOneGoodsService(Map<String, Object> condMap)
	{
		return this.goodsDao.findOne(condMap);
	}
	
	@Override
	public JSONObject saveOneGoodsService(AGoods goods)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsDao.save(goods);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goods.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	/**
	 * 保存一条商品
	 * @param goods	保存的对象
	 * @return	json:{"code":"0","info":"成功","data":{"effect":"","id":""}}
	 */
	public JSONObject saveOneGoodsService(AGoods goods,Map<String, Object> paramsMap)
	{
		JSONObject resultJSON = this.saveOneGoodsService(goods);
		return resultJSON ; 
	}
	
	@Override
	public JSONObject updateOneGoodsService(AGoods goods)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsDao.update(goods);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goods.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneGoodsService(AGoods goods)
	{
		JSONObject resultJSON = new JSONObject();
		return resultJSON;
	}
	
	/*
	 * 查询列表时，先查redis中的数据：存在，则查redis，不存在，查数据库，放到redis中
	 * */
	@Override
	public Map<String, Object> findCondListGoodsService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		/*redis的键*/
		String redisKey = "goodList_" + condMap.get("cateId") + "_" + pageInfoUtil.getCurrentPage(); 
		/* 为关键字加上%,实现模糊匹配 
		 * */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		Map<String, Object> resultMap = new HashMap<>();
		if(pageInfoUtil != null)
		{
			/*查询是否有该键对应的值存在*/
			String resultJSONStr = this.redisUtil.get("redisKey");
			/*-------------------------存在，从redis中取值----------------------*/
			if(resultJSONStr != null && !"".equalsIgnoreCase(resultJSONStr)){
				JSONObject resultJSON = (JSONObject) JSON.parse(resultJSONStr);
				/*解析数据，需要拼装两个数据，一个是goodList,一个是totalRecord*/
				if(resultJSON != null && "0".equalsIgnoreCase(resultJSON.get("code") + "")){
					/*查询成功*/
					JSONObject dataJSON = (JSONObject) resultJSON.get("data");
					/*分页信息*/
					JSONObject pageInfoJSON = (JSONObject) dataJSON.get("pageInfo");
					/*将pageInfoUtil转换成对象*/
					pageInfoUtil = new PageInfoUtil();
					pageInfoUtil.parseJSON(pageInfoJSON);
					resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
					
					List<AGoods> goodsList = new ArrayList<>();
					/*数据*/
					JSONArray goodsArr = (JSONArray) dataJSON.get("goodsList");
					for (Iterator iterator = goodsArr.iterator(); iterator.hasNext();)
					{
						JSONObject goodsJSON = (JSONObject) iterator.next();
						AGoods goods = new AGoods();
						goods = goods.parseJSON(goodsJSON);
						goodsList.add(goods);
					}
					resultMap.put("list", goodsList);
					return resultMap;
				}
			}
			/* 分页 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			/* 查询总记录数 */
			List<AGoods> goodsList = this.goodsDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Long.valueOf(page.getTotal()).intValue());
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			resultMap.put("list", goodsList);
			/*--------------------redis没有查到，往redis中放置----------------------*/
			/*格式如下：拼装JSON，放入redis
			 * {
					“code”:”0”,
					“info:””,
					“data”:
					{
					   “goodsList”:
						[
						{}
						],
						“pageInfo”:{
						}
					}
				}
			 */
			JSONObject resultJSON = new JSONObject();
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			/*数据*/
			JSONObject dataJSON = new JSONObject();
			JSONArray goodsArr = new JSONArray();
			/*循环goodsList，取到goods对象，转换成json对象添加到goodsArr中*/
			for (Iterator iterator = goodsList.iterator(); iterator.hasNext();)
			{
				AGoods goods = (AGoods) iterator.next();
				goodsArr.add(goods.toJSON());
			}
			dataJSON.put("goodsList", goodsArr);
			/*放置分页对象*/
			dataJSON.put("pageInfoUtil", pageInfoUtil.toJSON());
			resultJSON.put("data", dataJSON);
			/*将拼装的JSON存储到redis中*/
			this.redisUtil.set(redisKey, resultJSON.toJSONString(), 
					Integer.valueOf(ConstatFinalUtil.CONFIG_JSON.get("password.error.lockTime") + ""));
			return resultMap;
		}
		/* 不分页查询数据 */
		List<AGoods> goodsList = this.goodsDao.findList(condMap);
		resultMap.put("list", goodsList);
		return resultMap;
	}
	
	/**
	 * 商品模块结束
	 */
}
